import React from 'react'
import _ from 'underscore'
import View from 'lib/View.jsx'
import Layout from '../common/layout.jsx'
import dispatcher from 'lib/dispatcher'
import Card from 'lib/components/card.jsx'
import Grid from 'lib/components/GridWidget.jsx'
import format from 'lib/util/format'
import Scope from './Scope.es6'
import AppSetting from './AppSetting.jsx'
import DashboardSetting from './DashboardSetting.jsx'
import {delAccountApi} from '../apis/validApis/account'
import {delDashboardApi} from '../apis/validApis/dashboard'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import {Confirm} from 'lib/components/Confirm.jsx'
import DownloadAndroidView from './DownloadAndroidView.jsx'
import cx from 'classnames';

var appListColsOption = [{
  key:'appType',
  width: 24,
  render:function(fmtVal){
    if(fmtVal === 'Android'){
      return (
        <i className="iconfont">&#xe66c;</i>
      )
    }else if(fmtVal === 'iOS'){
      return (
        <i className="iconfont">&#xe66b;</i>
      )
    }
    return null
  }
},{
  title:'应用名称',
  key:'accountName',
  sortable:true,
  containerStyle: {
    minWidth: 100
  },
  render:function(fmtVal,rowData,rowIndex,colIndex){
    return (
      <p>
        <a href={BlueWare.pageUrlPrefix+'/app/'+rowData.appId+'/overview'}>{fmtVal}</a>
      </p>
    )
  }
},{
  title:'活跃版本数',
  width: '10%',
  sortable:true,
  key:'activeVersionNum'
},{
  title:'包名',
  width: '25%',
  sortable:true,
  key:'appPgkName'
},{
  title:'崩溃次数',
  width: '10%',
  sortable:true,
  key:'crashCount',
  formatter:format.integer
},{
  title:'HTTP错误率',
  width: '10%',
  sortable:true,
  key:'httpErrorRate',
  formatter:format.rate
},{
  title:'网络错误率',
  width: '10%',
  sortable:true,
  key:'netWorkErrorRate',
  formatter:format.rate
}
// ,{
//  title:'新增设备数',
//  width: '10%',
//  sortable:true,
//  key:'newDeviceNum',
//  formatter:format.integer
// }
,{
  title:'活跃设备数',
  width: '10%',
  sortable:true,
  key:'activeDeviceNum',
  formatter:format.integer
}
// ,{
//   title:'创建时间',
//   width: 120,
//   key:'createTime',
//   sortable:true,
//   formatter:format.stampToTime
// }
,{
  key:'fdsfds',
  width: 90,
  render:function(fmtVal,rowData,rowIndex,colIndex){
    function showSetting(){
      AppSetting.mount({
        appId:rowData.accountId,
        appName:rowData.accountName
      })
    }
    var delApp = function delApp(){
      Confirm(<p>确定要删除吗？</p>).then(function(){
        delAccountApi({
          id:rowData.accountId
        }).post().then(function(res){
          if(res.result){
            Success('删除成功！')

            // 逻辑修复：服务器端删除成功后才移除掉该信息（同#line: 201）
            dispatcher.dispatch({
              $type:'delete_app',
              id:rowData.accountId
            })
          }else{
            Warning('删除失败！')
          }
        },function(){
          Warning('删除失败！')
        })
      })
    }

    let userId = _.last(BlueWare.urlPrefix.split('/'));
    return (
      <div className="operation">
        {
          rowData.appType === 'Android' && userId === '723'
            ? (<a
                className="iconfont icon-download"
                onClick={()=> DownloadAndroidView.mount()}
                data-tip="下载安卓版应用"
                href="javascript:;"></a>)
            : null
        }
        <a className="iconfont" onClick={showSetting} href="javascript:;">&#xe61e;</a>
        <a className="iconfont" onClick={delApp} href="javascript:;">&#xe61f;</a>
      </div>
    )
  }
}]

class AppGrid extends Grid {
  renderRow(rowData,rowIndex){
    if(rowData.appId===0){
      var setupUrl = BlueWare.pageUrlPrefix+'/app/setup?id='+rowData.accountId
      return (
        <tr key={rowIndex}>
          <td key="av">
            <i className="iconfont"></i>
          </td>
          <td key="a">
            <a href={setupUrl}>{rowData.accountName}</a>
          </td>
          <td key="b" colSpan={appListColsOption.length - 3}>此 app 尚无数据返回，<a href={setupUrl}>点击这里 </a>查看 agent 安装步骤</td>
          <td key="c">{appListColsOption[appListColsOption.length - 1].render(null,rowData,rowIndex,null)}</td>
        </tr>
      )
    }else{
      return super.renderRow(rowData,rowIndex)
    }
  }
}
var dashboardColsOption = [{
  title:'名称',
  key:'name',
  sortable:true,
  render:function(fmtVal,rowData){
    return (
      <a href={BlueWare.pageUrlPrefix+'/dashboard/'+rowData.id}>{fmtVal}</a>
    )
  }
},{
  title:'创建时间',
  key:'gmtCreateTime',
  sortable:true
},{
  title:'修改时间',
  key:'gmtModifyTime',
  sortable:true
},{
  key:'abc',
  render:function(fmtVal,rowData){
    function showSetting(){
      DashboardSetting.mount({
        dashboardName:rowData.name,
        dashboardId:rowData.id
      })
    }

    var delApp = function delApp(){
      Confirm('确定要删除吗？').then(function(){
          delDashboardApi({
            id:rowData.id
          }).post().then(function(res){
            if(res.result){
              Success('删除成功！')
              dispatcher.dispatch({
                $type:'delete_dashboard',
                id:rowData.id
              })
            }else{
              Warning('删除失败！')
            }
          },function(){
            Warning('删除失败！')
          })
      })
    }

    return (
      <div className="operation">
        <a className="iconfont" onClick={showSetting} href="javascript:;">&#xe61e;</a>
        <a className="iconfont" onClick={delApp} href="javascript:;">&#xe61f;</a>
      </div>
    )
  }
}]

export default class MainView extends View{
  constructor(props){
    super(props)
    this.showDashBoardAdd = this.showDashBoardAdd.bind(this)
  }
  showDashBoardAdd(){
    if(this.state.dashboardList.data&&this.state.dashboardList.data.length<5){
      DashboardSetting.mount({})
    }else{
      Warning('您只能添加5个仪表盘')
    }

  }
  render(){
    return (
      <div>
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card>
                <AppGrid cols={appListColsOption} store={this.state.appList}/>
              </Card>
            </div>
          </div>
        </div>
        <div className="page-title" style={{marginTop: '30px'}}>
          <div className="navbar">
            <a className="btn-green" href="javascript:;" onClick={this.showDashBoardAdd}>添加仪表盘</a>
          </div>
          <h2>仪表盘<sub>所有仪表盘</sub></h2>
        </div>
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card>
                <Grid cols={dashboardColsOption} store={this.state.dashboardList}/>
              </Card>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
MainView.defaultProps = {
  Scope:Scope
}
